﻿using System;
using System.Management;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using Microsoft.Win32;
using System.Text;
using System.Windows.Forms;
using System.Media;
using System.IO;
using Scripting;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Management;


namespace WindowsFormsApplication1
{
    public partial class UsbWindow : Form
    {
        ArrayList imageList;
        Form1 theForm1;
       public  ManagementEventWatcher w = null;

       public SelectQuery query;
       public ManagementObjectSearcher searcher;
       public ManagementOperationObserver observer;
       public WqlEventQuery q;
       public ManagementScope scope;
       bool eventh = false;


       public static System.Windows.Forms.Timer activityTimer = new System.Windows.Forms.Timer();

        public UsbWindow(Form1 aForm1, ArrayList aL)
        {
            InitializeComponent();



            activityTimer.Tick += activityWorker_Tick;
            activityTimer.Interval = 500;
            activityTimer.Enabled = true;



            imageList = aL;
            theForm1 = aForm1;

            listView1.TileSize = new System.Drawing.Size(100, 80);
            this.listView1.View = View.LargeIcon;
            this.listView1.LargeImageList = theForm1.imageList;

            int i = 0;

            ArrayList a = (ArrayList)imageList;

            foreach (object imageIndex in a)
            {
                listView1.Items.Add(theForm1.imageFileNameList[(int)imageIndex]);
                listView1.Items[i].ImageIndex = (int)imageIndex;
                i++;
            }

            ImageList aaaaa = new ImageList();

            aaaaa.ColorDepth = ColorDepth.Depth32Bit;
            aaaaa.ImageSize = new Size(100, 80); 

            Image dd = new Bitmap(Path.GetDirectoryName(Application.ExecutablePath).Replace("\\bin\\Debug", "\\Icons\\drive.jpg"));
            aaaaa.Images.Add(dd);

            listView2.TileSize = new System.Drawing.Size(100, 80);
            this.listView2.View = View.LargeIcon;
            this.listView2.LargeImageList = aaaaa;

            i = 0;


                                query = new SelectQuery("select name, FreeSpace from win32_logicaldisk where drivetype=2");
                    searcher = new ManagementObjectSearcher(query);

                    foreach (ManagementObject mo in searcher.Get())
                    {
                       // Console.WriteLine("Drive letter is: {0}", mo["name"]);
                       // Console.WriteLine("Drive's free space is: {0}", mo["FreeSpace"]);

                                        listView2.Items.Add((string)mo["name"]);
                       
                listView2.Items[i].ImageIndex = 0;
                i++;
                    }


                    if (listView2.Items.Count == 1)
                    {
                        listView2.Items[0].Selected = true;
                        listView2.Select();
                    }
    

            // from http://www.techtalkz.com/c-c-sharp/182048-need-detect-insertion-removal-usb-drive.html


      //      WMIEvent we = new WMIEvent();


observer = new ManagementOperationObserver();
// Bind to local machine
scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true; //sets requiredprivilege
try
{

q = new WqlEventQuery();
q.EventClassName = "__InstanceOperationEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = @"TargetInstance ISA 'Win32_DiskDrive' ";


//Console.WriteLine(q.QueryString);
w = new ManagementEventWatcher(q);


w.EventArrived += new EventArrivedEventHandler(this.UsbEventArrived);
w.Start();


}


catch (Exception e)
{
//Console.WriteLine(e.Message);

}










        }











        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            activityTimer.Stop();
            w.Stop();
            Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
         //   autoComplete1.Text.

            if (listView2.SelectedItems.Count > 0)
            {
                w.Stop();
                activityTimer.Stop();








                foreach (ListViewItem lvi in listView2.SelectedItems)
                {
                    // System.Console.WriteLine(lvi.Text);

                    string myDocspath = lvi.Text;



                    try
                    {


                        foreach (object imageIndex in imageList)
                        {
                            // Get the strings from the textboxes
                            string strOrigFile = theForm1.imageLocation[(int)imageIndex];
                            string strDestLoc = myDocspath + "\\";

                            // Get the filename only
                            string strFileName = System.IO.Path.GetFileName(strOrigFile);

                            // Determine the full destination path including filename
                            string strDestFile = System.IO.Path.Combine(strDestLoc, strFileName);
                            System.Console.WriteLine(strDestFile);
                            // Copy the file
                            System.IO.File.Copy(strOrigFile, strDestFile);
                        }


                    }
                    catch(Exception eee)
                    {
                        MessageBox.Show("Some of the pictures are already copied there.");
                    }



                    string windir = Environment.GetEnvironmentVariable("WINDIR");
                    System.Diagnostics.Process prc = new System.Diagnostics.Process();
                    prc.StartInfo.FileName = windir + @"\explorer.exe";
                    prc.StartInfo.Arguments = myDocspath;
                    prc.Start();



                }








                Close();
            }
            else
            {
                string soundClipLocation = Path.GetDirectoryName(Application.ExecutablePath).Replace("\\bin\\Debug", "\\Sounds\\ding.wav");
                SoundPlayer sp = new SoundPlayer(soundClipLocation);
                sp.Play();

                (new NoSelection()).ShowDialog();
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

            listView1.SelectedItems.Clear();
        }

    


        // from above site

        public void UsbEventArrived(object sender, System.Management.EventArrivedEventArgs e)
        {

 

          //  int i;
            
            try
            {

                ManagementBaseObject mbo = null;

                mbo = (ManagementBaseObject)e.NewEvent;
                if ((mbo.ClassPath.ClassName == "__InstanceCreationEvent"))
                {
                  //  this.Close();
               //     w.Stop();
                    eventh = true;
                    System.Console.WriteLine("Usb inserted");



                    

                    /*
                    listView2.Items.Clear();

                    
                    

                    query = new SelectQuery("select name, FreeSpace from win32_logicaldisk where drivetype=2");
                    searcher = new ManagementObjectSearcher(query);
                    i = 0;
                    foreach (ManagementObject mo in searcher.Get())
                    {
                        Console.WriteLine("Drive letter is: {0}", mo["name"]);
                        Console.WriteLine("Drive's free space is: {0}", mo["FreeSpace"]);

                        listView2.Items.Add((string)mo["name"]);

                        listView2.Items[i].ImageIndex = 0;
                        i++;
                    }
                    

                    
                    i = 0;


                    SelectQuery query = new SelectQuery("select name, FreeSpace from win32_logicaldisk where drivetype=2");
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

                    foreach (ManagementObject mo in searcher.Get())
                    {
                        // Console.WriteLine("Drive letter is: {0}", mo["name"]);
                        // Console.WriteLine("Drive's free space is: {0}", mo["FreeSpace"]);

                        listView2.Items.Add((string)mo["name"]);

                        listView2.Items[i].ImageIndex = 0;
                        i++;
                    }
                    */
                }
                else
                {
                    eventh = true;
                    System.Console.WriteLine("Usb removed");
                    /*
                    listView2.Items.Clear();
                    i = 0;


                    query = new SelectQuery("select name, FreeSpace from win32_logicaldisk where drivetype=2");
                    searcher = new ManagementObjectSearcher(query);

                    foreach (ManagementObject mo in searcher.Get())
                    {
                        // Console.WriteLine("Drive letter is: {0}", mo["name"]);
                        // Console.WriteLine("Drive's free space is: {0}", mo["FreeSpace"]);

                        listView2.Items.Add((string)mo["name"]);

                        listView2.Items[i].ImageIndex = 0;
                        i++;
                    }
                     */
                }

            }
            catch (Exception ee)
            { }
             


            /*
            

            listView2.Items.Clear();

           int i = 0;

            observer = new ManagementOperationObserver();
            query = new SelectQuery("select name, FreeSpace from win32_logicaldisk where drivetype=2");
            searcher = new ManagementObjectSearcher(query);
  

            foreach (ManagementObject mo in searcher.Get())
            {
                // Console.WriteLine("Drive letter is: {0}", mo["name"]);
                // Console.WriteLine("Drive's free space is: {0}", mo["FreeSpace"]);
               
                listView2.Items.Add(mo["name"].ToString());

                listView2.Items[i].ImageIndex = 0;
                i++;

                System.Console.WriteLine("fdaasfasfdsaf");
            }

            
            */


            
           // a.WindowState = System.Windows.Forms.FormWindowState.Minimized;

          //  a.Top = this.Top;
         //   a.Left = this.Left;
//
            
        //    listView2.Clear();
         //   listView2 = a.listView2;
        //    listView2.Refresh();


        }


        // Handle Closing of the Form.
        protected override void OnClosing(CancelEventArgs e)
        {
            w.Stop();
            activityTimer.Stop();
            base.OnClosing(e);
        }



        void activityWorker_Tick(object sender, EventArgs e)
        {
            if (eventh)
            {


                w.Stop();
                this.Visible = false;

                


                eventh = false;
                UsbWindow a = new UsbWindow(theForm1, imageList);

                a.StartPosition = FormStartPosition.Manual;

                a.Location = this.Location;
                a.WindowState = this.WindowState;

                a.ShowDialog(theForm1);

                activityTimer.Enabled = false;
                activityTimer = new System.Windows.Forms.Timer();

                

                //button2_Click(null, null);
                //  w.Dispose();
                //  this.Close();
            }
        }


    }
}
